//是否点击拉框
var dragzoomActive = false;
//地图公共类
var mapUtil = {
	drawLayer: null,
	drawInteraction: null,
	drawedFeature: null,
	selectFeatue:null,
	selectevent:null,
	initializeMap: function(){
        window.olGis = new OLGIS();
        olGis.initMap('map');
        map = olGis.map;
        olGis.addMapScaleLine();
        olGis.addMapMouseControl();
                      
        olGis.addBaseLayer();//OSM底图
     
       	olGis.addTDTLayer();//添加影像图
             
        map.getView().setCenter([122.34, 43.60]);
        this.zoomOut();
        this.zoomIn();
        this.viewIn();
        this.initdragZoom();
    },
    initdragZoom: function(){
    	if(!document.querySelector("#dragIn")){
    		return;
    	}
    	var dragZoom = new ol.interaction.DragZoom({
	        condition: ol.events.condition.always,
	        out: false, // 此处为设置拉框完成时放大还是缩小
      	});
      	map.addInteraction(dragZoom);
      	dragZoom.setActive(false);
      	
      	// 绑定放大缩小按钮事件
        document.querySelector("#dragIn").addEventListener('click', function() {
	        if (dragzoomActive) {
	          dragZoom.setActive(false);
	          dragzoomActive = false;
	          document.querySelector("#map").style.cursor = "default";
	        } else {
	          dragZoom.G = false;
	          dragZoom.setActive(true);
	          dragzoomActive = true;
	          document.querySelector("#map").style.cursor = "crosshair";
	        }
        }, false);
    },
    //地图层级放大
    zoomOut: function(){    	
    	 $("#zoomOut").click(function(){
    		var currentZoom = map.getView().getZoom();
    		map.getView().setZoom(currentZoom + 1);
        });
    },
    //地图层级缩小
    zoomIn: function() {
    	
    	 $("#zoomIn").click(function(){
    		var currentZoom = map.getView().getZoom();
    		map.getView().setZoom(currentZoom - 1);
        });
    },
    //恢复原始试图
    viewIn: function(){
    	$("#viewIn").click(function(){
//    		debugger
        /*	var url = htport + '/mapset/getInfo.html';
        	var position = [];
        	$.get(url,function(data){
        		for(var i =0, data = data.rows; i < data.length; i++){
        			if (data[i].ifcheck == 1) {
        				position.push(data[i].lon,data[i].lat);
        			}
        		}
        		
        	});*/
        	
//        	map.getView().fit(position, map.getSize());
			
        	map.getView().setCenter([122.34, 43.60]);
       		map.getView().setZoom(10);
       });
    },
    //创建绘制的feature的layer
    createDrawFeature: function(){
    	var drawLayer = new ol.layer.Vector({
	      source: new ol.source.Vector(),
	      style: new ol.style.Style({
	        stroke: new ol.style.Stroke({
	          color: 'blue',
	          width: 5
	        })
	      })
	    });
    	return drawLayer;
    },
    // 添加绘制新图形的interaction，用于添加新的线条
    createDrawInteraction: function(type, drawLayer){
    	var type = type || 'LineString';
    	var drawInteraction = new ol.interaction.Draw({
	      type: type, // 设定为线条
	      style: new ol.style.Style({
	        stroke: new ol.style.Stroke({
	          color: 'red',
	          width: 10
	        })
	      }),
	      source: drawLayer.getSource()
	    });
	    drawInteraction.on('drawend', function(e) {
	      // 绘制结束时暂存绘制的feature
	      drawedFeature = e.feature;
	    });
	    return drawInteraction;
    },
    //创建GeojsonLaye
    addGeojsonLayer: function(layername, geojsonObj){
    	return olGis.addGeojsonLayer(layername, geojsonObj);
    },
    addGeojsonLayerByUrl: function(layername, url, styleCall){
    	return olGis.addGeojsonLayerByUrl(layername, url, styleCall);
    },
     //创建nodeslayer
    addNodesLayer: function(){
    	return olGis.addNodesLayer();
    },
     //添加选择事件
    createSelectSingleClick: function(callbackFun){
    		var selevent = new SelectFeatureEvent(map);
    		selevent.selectEvent(callbackFun);
    		this.selectevent = selevent;
    		this.selectFeatue = selevent.selectFeatue;
    },
    
    //del选择事件
    removeSelectSingleClick: function(){
    	if(this.selectevent){
    		this.selectevent.removeSelectEvent();
            this.selectFeatue = null;
        }
    },
     //add选择事件
    addSelectSingleClick: function(){
    	if(this.selectevent){
    		
    		this.selectevent.selectEvent(this.selectevent.overlayContent);
    	}
    },
    //鼠标单击事件若该元素为选中状态清除选中元素
    singleClick : function(vlayer, select){
        map.on("click", function(e){
            var feature = map.forEachFeatureAtPixel(e.pixel,
                function(feature, layer){
                    if(vlayer == layer){
                        var selfeatures = select.getFeatures();
                        if(selfeatures&&selfeatures.getLength() > 0){
                            var arr = selfeatures.getArray();
                            if(arr[0].get("id") == feature.get("id")){
                                //清除选中元素
                                select.getFeatures().clear();
                            }
                        }
                    }
                });
        });
    }

};


//图层显示隐藏
 function checkLayer(obj, layerId){
 	
 	   	var layers = window.olGis.layerlist;//map.getLayers();
 	   	for (i = 0; i < layers.length; i++) {
 	   		 // code to be executed
 	   		 if(layerId == layers[i][0]){
 	   		 		
 	   		 		var layer = layers[i][2];
 	   		 		if(layer){
 	   		 			layer.setVisible(obj.checked);
 	   		 		}
 	   		 		break;
 	   		 }
 	   	}
}


//设置矢量图置顶
function upSlt(obj, layerId){
 	if (obj.checked) {
 		var layers = window.olGis.layerlist;
 		for (i = 0; i < layers.length; i++) {		
 			var layer = layers[i][2];
 			var index = layer.getZIndex();
 	   	if(layerId == layers[i][0]){ 
 	   		layer.setZIndex(layers.length);
 	   	}else{
 	   		layer.setZIndex(index-1);
 	   	}
 	   }
 	} 	
} 
 
//经纬度定位
function positionPark(){
    var lon = $('#lon').val();
    var lat = $('#lat').val();
	map.getView().setCenter([lon,lat]);
	map.getView().setZoom(10);
}

//测量相关
var measureUtil = {
    //测量VectorLayer
    measureLayer: null,
    //临时interaction
    draw: null,
    /**
     * The measure tooltip element.
     * @type {Element}
     */
    measureTooltipElement: null,
    /**
     * Overlay to show the measurement.
     * @type {ol.Overlay}
     *
     */
    measureTooltip: null,
    /**
     * Currently drawn feature.
     * @type {ol.Feature}
     */
    sketch: null,
    /**
     * The help tooltip element.
     * @type {Element}
     */
    helpTooltipElement: null,
    /**
     * Overlay to show the help messages.
     * @type {ol.Overlay}
     */
    helpTooltip: null,
    /**
     * Message to show when the user is drawing a polygon.
     * @type {string}
     */
    continuePolygonMsg : '点击继续绘制面积',
    /**
     * Message to show when the user is drawing a line.
     * @type {string}
     */
    continueLineMsg : '点击继续绘制',
     /**
     * pointerMoveHandler 事件监听.
     * @type {string}
     */
    pointerMoveListener : null,
    /**
     * Handle pointer move.
     * @param {ol.MapBrowserEvent} evt The event.
     */     
    pointerMoveHandler: function(evt){

        if (evt.dragging) {
            return;
        }
        var helpMsg = '点击开始绘制';
        if (measureUtil.sketch) {
            var geom = (measureUtil.sketch.getGeometry());
            if (geom instanceof ol.geom.Polygon) {
                helpMsg = measureUtil.continuePolygonMsg;
            } else if (geom instanceof ol.geom.LineString) {
                helpMsg = measureUtil.continueLineMsg;
            }
        }

        measureUtil.helpTooltipElement.innerHTML = helpMsg;
        measureUtil.helpTooltip.setPosition(evt.coordinate);
        measureUtil.helpTooltipElement.classList.remove('hidden');
    },
    clearLayer: function(){
        if (this.measureLayer) {
//        	 this.measureLayer = null;
//             this.draw = null;
        	debugger
        	
          map.removeInteraction(this.draw);
        	map.removeLayer(this.measureLayer);
        	
        	this.draw = null;
        	this.measureLayer = null;
        	
        	this.removeInteraction();
        	ol.Observable.unByKey(this.pointerMoveListener);
        	this.pointerMoveListener = null;
        	
        	//添加正常地图交互
        //	map.addInteraction(selectSingleClick);
        	$('.tooltip').parent().remove();
        	
          }
         /// mapUtil.addSelectSingleClick();
          
    },
    measure: function(geomtryType) {
    	
    	 	mapUtil.removeSelectSingleClick();
				drawGeom.removeDrawInteraction();
				
        this.removeInteraction();


        var geomtryType = geomtryType || 'LineString'; //Polygon  LineString
        var source = new ol.source.Vector();
        if (this.measureLayer) {

        } else {
            this.measureLayer = new ol.layer.Vector({
                source: source,
                style: new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#ffcc33',
                        width: 2
                    }),
                    image: new ol.style.Circle({
                        radius: 7,
                        fill: new ol.style.Fill({
                            color: '#ffcc33'
                        })
                    })
                })
            });
            map.addLayer(this.measureLayer);
        }
        	if(!this.pointerMoveListener){
								this.pointerMoveListener = map.on('pointermove', this.pointerMoveHandler);
				}      

        var _this = this;
        map.getViewport().addEventListener('mouseout', function() {
            _this.helpTooltipElement.classList.add('hidden');
        });

        this.addInteraction(geomtryType);
        
        
    },
    //EPSG:3857计算方式
    formatEPSG3857Length: function(line) {
    	debugger
        var length=Math.round(line.getLength()*100)/100;
        var output;
        if (length > 100) {
            output = (Math.round(length / 1000 * 100) / 100) +
                ' ' + 'km';
        } else {
            output = (Math.round(length * 100) / 100) +
                ' ' + 'm';
        }
        return output;
    },
    //EPSG:4326计算方式
    formatLength: function(line) {

    	var wgs84Sphere = new ol.Sphere(6378137);
    	var lineCoordinates = line.getCoordinates();
    	var length = 0;
    	for (var i = 0; i < lineCoordinates.length - 1; i += 1) {
            length += wgs84Sphere.haversineDistance(lineCoordinates[i], lineCoordinates[i + 1]);
        }
    	
    	if (length > 1000) {
            length = (length / 1000).toFixed(2);
            unit = 'km';
            output = length + unit;
            
        } else {
            unit = 'm';
            output = length.toFixed(2) + unit;
        }
    	
//    	var wgs84Sphere = new ol.Sphere(6378137); 
//    	
//    	wgs84Sphere.haversineDistance(line.getCoordinates()[0],line.getCoordinates()[1]);
//    	
//    	debugger
//        var length=Math.round(line.getLength()*100)/100;
//        var output;
//        if (length > 100) {
//            output = (Math.round(length / 1000 * 100) / 100) +
//                ' ' + 'km';
//        } else {
//            output = (Math.round(length * 100) / 100) +
//                ' ' + 'm';
//        }
        return output;
    },
    //3857计算面积
    formatEPSG3857Area: function(polygon) {
        var area=polygon.getArea();
        var output;
        if (area > 10000) {
            output = (Math.round(area / 1000000 * 100) / 100) +
                ' ' + 'km<sup>2</sup>';
        } else {
            output = (Math.round(area * 100) / 100) +
                ' ' + 'm<sup>2</sup>';
        }
        return output;
    },
    //EPSG:4326计算面积
    formatArea: function(polygon) {
    	var output;
    	var wgs84Sphere = new ol.Sphere(6378137);
    	var lonLatPolygon  = polygon.getCoordinates();
    	
    	var area = Math.abs(wgs84Sphere.geodesicArea(lonLatPolygon[0]));
    	
    	if (area > 1000000) {
            area = (area / 1000000).toFixed(2);
            unit = 'km²';
            output = area + unit;
        } else {
            unit = 'm²';
            output = area.toFixed(2) + unit;
        }
    	
    	
//        var area=polygon.getArea();
//        var output;
//        if (area > 10000) {
//            output = (Math.round(area / 1000000 * 100) / 100) +
//                ' ' + 'km<sup>2</sup>';
//        } else {
//            output = (Math.round(area * 100) / 100) +
//                ' ' + 'm<sup>2</sup>';
//        }
        return output;
    },
    addInteraction: function(type) {

        this.draw = new ol.interaction.Draw({
            source: this.measureLayer.getSource(),
            type: /** @type {ol.geom.GeometryType} */ (type),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    stroke: new ol.style.Stroke({
                        color: 'rgba(0, 0, 0, 0.7)'
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    })
                })
            })
        });
        map.addInteraction(this.draw);

        this.createMeasureTooltip();
        this.createHelpTooltip();

        var listener;
        var _this = this;
        this.draw.on('drawstart',
            function(evt) {
                this.sketch = evt.feature;

                /** @type {ol.Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;

                listener = this.sketch.getGeometry().on('change', function(evt) {
                    var geom = evt.target;
                    var output;
                    if (geom instanceof ol.geom.Polygon) {
                        output = _this.formatArea(geom);
                        tooltipCoord = geom.getInteriorPoint().getCoordinates();
                    } else if (geom instanceof ol.geom.LineString) {
                    	
                        output = _this.formatLength(geom);
                        tooltipCoord = geom.getLastCoordinate();
                        
                    }
                    _this.measureTooltipElement.innerHTML = output;
                    _this.measureTooltip.setPosition(tooltipCoord);
                });
            }, this);

        this.draw.on('drawend',
            function() {
                this.measureTooltipElement.className = 'tooltip tooltip-static';
                this.measureTooltip.setOffset([0, -7]);
                // unset sketch
                this.sketch = null;
                // unset tooltip so that a new one can be created
                this. measureTooltipElement = null;
                this.createMeasureTooltip();
                ol.Observable.unByKey(listener);
            }, this);
    },
    createHelpTooltip: function(){
        if (this.helpTooltipElement) {
            this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement);
        }
        this.helpTooltipElement = document.createElement('div');
        this.helpTooltipElement.className = 'tooltip hidden';
        this.helpTooltip = new ol.Overlay({
            element: this.helpTooltipElement,
            offset: [15, 0],
            positioning: 'center-left'
        });
        map.addOverlay(this.helpTooltip);
    },
    createMeasureTooltip: function(){
        if (this.measureTooltipElement) {
            this.measureTooltipElement.parentNode.removeChild(this.measureTooltipElement);
        }
        this.measureTooltipElement = document.createElement('div');
        this.measureTooltipElement.className = 'tooltip tooltip-measure';
        this.measureTooltip = new ol.Overlay({
            element: this.measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        map.addOverlay(this.measureTooltip);
    },
    removeInteraction: function(){
        map.removeInteraction(this.draw);
    }
};

//默认 不勾选其他图层
var mapLayerUtils = {
	removeLayerCheckbox: function(){
		$('#dxtChk').click();  
		 $('#wptChk').click();   
		 $('#sxtChk').click();   
		 $('#zwtChk').click();   
		 $('#dwtChk').click();   
		 $('#gnqhtChk').click();   
		 $('#gnqwtChk').click();   
		 $('#rhyxChk').click();   
		 $('#yxtChk').click();
	}
};


function initCmdButton(){
	
	
	drawGeom.removeDrawInteraction();
	measureUtil.removeInteraction();
}


function resetCmd(){
	
	measureUtil.clearLayer();
	drawGeom.removeDrawInteraction();
	mapUtil.addSelectSingleClick();
	
}
